#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#include "featurepp.h"

/* Arguments:
     - argv[1]: 1 for repair, everything else for failure
     - argv[2]: CSV-sourcefile
     - argv[3]: Outputfile
*/
/* NOTE: 1 for repair means whenever the validator discovers an issue, it
tries to fix it up.If anything else is set, the validator will exit with an error message.
*/

main(int argc, char *argv[]) {
   
   FILE *fpsource, *fpoutput, *fpoutput2;

   char t[1000];                    // Buffer
   char eins[] = "1";               // Liadan requires points weighted by one
   char zero[] = "0";               // used for repairing
   
   int repair;
   int n = 0;
   int d = -1;
   int i, j = 0;


   if (argc!=4) {
   	printf("usage: csv2wsv 1 csvsourcefile outputfile\n");
   	exit(1);
   }   
      
   if (strcmp(argv[1], "1") == 0) {
  	repair = 1;
   }
    
//   printf("Open: %s\n", argv[2]);
   if ((fpsource = fopen(argv[2], "r"))==NULL) {
      printf("error: can't open Sourcefile %s\n", argv[2]);
      exit(1);
   }

   /* for Streaming and Liadan */
//   printf("Open: %s\n", argv[3]);
   if ((fpoutput = fopen(argv[3], "w"))==NULL) {
      printf("error: can't open Sourcefile %s\n", argv[3]);
      exit(1);
   }

   strcat(argv[3],".b");

   /* for BIRCH */
//   printf("Open: %s\n", argv[3]);
   if ((fpoutput2 = fopen(argv[3], "w"))==NULL) {
      printf("error: can't open Sourcefile %s\n", argv[3]);
      exit(1);
   }


   while(readArg(t, fpsource)!=EOF) {
      writeArg(eins, fpoutput, ' ');      // set pointweight 1
      writeArg(t, fpoutput, ' ');         // write 1st coordinate
      writeArg(t, fpoutput2, ' ');
      i = 1;
      while(readArg(t, fpsource)==',') {     
         writeArg(t, fpoutput, ' ');      // write following coordinates
         writeArg(t, fpoutput2, ' ');  
         i++;
      }
      n++;
      if (d == -1) {
         d = (i+1);
      } else {
         if (d != (i+1)) {
             if (!repair) {
             	printf("failure! (only %d dimensions on value %d!)\n", (d-1), n);
	            exit(1);
             } else {
             	for (j = 0; j < d - i - 2; j++) {  //perform repair
             		writeArg(zero, fpoutput, ' ');
             		writeArg(zero, fpoutput2, ' ');
             	}
			writeArg(zero, fpoutput, ' ');
			writeArg(zero, fpoutput2, ' ');
             }
         } 
      }
      writeArg(t, fpoutput, '\n');        // write last coordinate + return
      writeArg(t, fpoutput2, '\n');

   }

   printf("%d %d", n, d);
   fclose(fpsource);
   fclose(fpoutput);
   fclose(fpoutput2);
   
   return 0;
}
